<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core"  prefix="c"%> 
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>后台系统</title>
   	<base href="${Context}">
 	<link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap-theme.min.css">
    <link rel="stylesheet" type="text/css" href="bootstrap/css/alertify.core.css">
    <link rel="stylesheet" type="text/css" href="bootstrap/css/alertify.default.css">
   	<link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap-table.min.css">
    <script type="text/javascript" src="js/jquery-1.11.3.js"></script>
    <script type="text/javascript" src="bootstrap/js/bootstrap.min.js"></script>
    <script type="text/javascript" src="bootstrap/js/alertify.min.js"></script>
    <script type="text/javascript" src="bootstrap/js/bootstrap-table.min.js"></script>
    <script type="text/javascript" src="bootstrap/js/bootstrap-table-zh-CN.min.js"></script>
    <style type="text/css">
        .InfoText {
            color: #B8860B;
            font-size: 16px;
            font-weight: 500;
        }
        .playerInfo{
        	margin: 0px 10px;
        	color: red;
        }
    </style>
</head>
<c:if test="${user.userType==0 }">
	<script type="text/javascript">
	$(function(){
		$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
		  if(e.target==$("#createSubAgentTab")[0]){
			  alertify.alert("抱歉!您还没有权限使用此功能!",function(){
				  $(e.relatedTarget).tab('show');
			  });
		  }
		});
		
	})
	</script>
</c:if>
<body style="height: 99%;">
  <!-- Nav tabs -->
  <ul class="nav nav-tabs" role="tablist">
    <li role="presentation" class="active"><a href="#member" aria-controls="member" role="tab" data-toggle="tab">子成员管理</a></li>
    <li role="presentation"><a href="#createMember" id="createSubAgentTab" aria-controls="createMember" role="tab" data-toggle="tab">创建子代理</a></li>
  </ul>

  <!-- Tab panes -->
  <div class="tab-content">
    <div class="tab-pane active panel panel-default" role="tabpanel" id="member">
	  <div class="panel-heading">
	    <div class="InfoText">剩余钻石：<span id="Balance" class="InfoText">${user.agentCoin }</span></div>
	  </div>
	  <table id="infoTable">
	 	
	  </table>

	</div>
   <div class="tab-pane panel panel-primary" role="tabpanel" id="createMember">
	  <div class="panel-heading">
	    <div class="InfoText">剩余钻石：<span id="Balance" class="InfoText">${user.agentCoin }</span></div>
	  </div>
	  <div class="panel-body">
	  	<form class="form-horizontal">
		  <div class="form-group">
		    <div class="col-sm-6 ">
		     <input type="text" class="form-control" id="playerId" placeholder="请输入下级代理游戏ID" aria-describedby="inputSuccess4Status">
		    </div>
		    <div class="collapse" id="toggleInfoDiv">
			  <div class="well"  id="toggleInfoWell">
			   未查询到玩家信息
			  </div>
			</div>
		    <div class="col-sm-4">
		    <input type="button" value="获取玩家信息" class="form-control btn btn-primary" onclick="searchPalyer($('#playerId').val());">
		    </div>
		  </div>
    	 <div class="form-group">
    	  	<div class="col-sm-8">
		      <input type="text" id="phone" class="form-control col-sm-8" pattern="[0-9A-Za-z]{11,11}" maxLength="11" placeholder="请输入下级代理手机号码(登录账号)"/>
		    </div>
		 </div>
		 <div class="form-group">
		    <div class="col-sm-8">
		      <input type="text" id="clubName" class="form-control col-sm-8" placeholder="请输入下级代理俱乐部名称"/>
		    </div>
    	 </div>
    	 <div class="form-group">
	    	 <div class="col-sm-8">
	         	<input type="button" value="提交" class="form-control btn btn-primary" onclick="submitCreateAgent();" aria-describedby="helpBlock">
	         	<span id="helpBlock" class="help-block">创建下级代理将扣除您600钻石,充值到下级代理账号中</span>
	         </div>
    	 </div>
	  </div>
	</div>
  </div>

</body>
<script>
var sys=sys || {};
sys.context = "${Context}";
sys.contextPath="${ContextPath}";
$.fn.addInputSuccess=function(){
	$(this).parent().append('<span class="glyphicon glyphicon-ok form-control-feedback" aria-hidden="true"></span>'
			  +'<span id="playerIdSuccessStatus" class="sr-only">(success)</span>').addClass("has-success has-feedback");
	$(this).attr("aria-describedby","playerIdSuccessStatus");
}
$.fn.removeInputSuccess=function(){
	$(this).parent().removeClass("has-success has-feedback").find('.glyphicon-ok').remove();
	$(this).parent().find(".sr-only").remove();
	$(this).removeAttr("aria-describedby");
}
alertify.set({
	labels : {
		ok     : "确认",
		cancel : "取消"
	},
	delay : 5000,
	buttonReverse : false,
	buttonFocus   : "ok"
});
    $(function () {
    	$("input").on('click',function(){
    		$("#toggleInfoDiv").collapse("hide");
    	});
    	loadSub();
    	
    	
    	
    });
	function searchPalyer(id){
    	
    	if(!id){
    		alertify.alert("请输入玩家游戏ID");
    		return false;
    	}
    	
    	if($("#toggleInfoWell").data("player") && $("#toggleInfoWell").data("player").id==id){
    		$("#toggleInfoDiv").collapse("show");
    		return true;
    	}else{
    		$("#toggleInfoWell").removeData("player");
        	$("#toggleInfoWell").html("未查询到玩家信息");
        	$("#playerId").removeInputSuccess();
    	}
    	$.post(sys.context+"main/searchPlayerInfo",{"playerId":id},function(data){
    		if(data.data){
    			var player=data["data"];
    			$("#toggleInfoWell").html("游戏名称:<span class='playerInfo'>"+player["nickName"]+"</span>");
    			$("#playerId").addInputSuccess();
    			$("#toggleInfoWell").data("player",player);
    			$("#toggleInfoDiv").collapse("show");
    		}else{
    			alertify.alert(data["msg"]);
    		}
    	},"json");
    	return true;
    }
	function submitCreateAgent(){		
		var phone=$("#phone").val(),clubName=$("#clubName").val(),player=$("#toggleInfoWell").data("player");
		if(!player && $("#playerId").val()){
			alertify.alert("请获取玩家信息!");
			return false;
		}
		if(!clubName||!phone){
			alertify.alert("请完整填写创建信息!");
			return false;
		}
		if(!(/^1[34578]\d{9}$/.test(phone))){
			alertify.alert("手机号码错误!请重新填写");
			return false;
		}
		var flag=false;
		$.when($.post(sys.context+"main/checkAgentPhone",{"phone":phone},function(data){
			if(data["error"]){
				alertify.alert(data["msg"]);
				flag=true;
				return false;
			}
		},"json")).done(function(){
			if(!flag){
				alertify.confirm("创建下级代理将从本账户上扣除600钻石为其充值,是否确认?",function(e){
					if(e){
						var param= {"playerId":player.id,"account":phone,"clubName":clubName};
						$.post(sys.context+"main/createSubAgent",param,function(data){
							alertify.alert(data["msg"]);
						},"json");
					}else{
						alertify.error("您取消了创建!");
					}
				});
			}else{
				return false;
			}
		});
		
	}
	
	
	function loadSub(){
		var queryParams=function (params) {
			console.log(params);
	        var temp = {   //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
	                limit: params.limit,   //页面大小
	                offset: params.offset||1,  //页码
	            };
	            return temp;
	        };
		$('#infoTable').bootstrapTable({
			url: sys.context+'main/getSubAgentPage',
			method: 'post',
			cache: false,
			pagination: true,
			queryParams: queryParams,
			sidePagination: "server",
			onLoadSuccess:function(data){
				$("#Balance").text(data.managerDiamond);
			},
			pageNumber:1,
			pageSize: 10,                       //每页的记录行数（*）
            pageList: [10, 25, 50, 100],
		    columns: [{
		        field: 'userId',
		        title: 'ID',
		        width: '20%',
		        align: 'center'
		    },{
		        field: 'userAccount',
		        title: '账号',
		        width: '20%',
		        align: 'center'
		    }, {
		        field: 'playerId',
		        title: '游戏ID',
		        align: 'center'
		    }, {
		        field: 'agentCoin',
		        title: '钻石',
		        align: 'center'
		    }, {
		        title: '操作',
		        align: 'center',
		        width: '20%',
		        formatter:function(v,r,i){
		        	return "<input type='button' class=btn btn-primary onclick='saleToSubAgent("+r.userId+")' value=充值>";
		        }
		    }],
		    data: [{
		    	userAccount: "-",
		    	userName: '-',
		    	playerId: '-',
		    	agentCoin: '-'
		    }]
		});
	}
	function saleToSubAgent(subAgentId){
		if(!subAgentId){
			alertify.error("数据错误!请刷新页面");
			return false;
		}
		alertify.prompt("请输入您需要出售的钻石数额",function(evt,value){
			if(evt && parseInt(value)>0 && !isNaN(value)){
				$.post(sys.context+"main/saleToSubAgent",{"subAgentId":subAgentId,"diamond":value},
						function(data){
					alertify.alert(data["msg"],function(){
						console.log(1);
						 $('#infoTable').bootstrapTable('refresh',{silent: true});
					});
				},"json");
			}else{
				alertify.error("您取消了出售!");
			}
		},"10");
	}
	
	function formatRecordStates(value, row, index){
		if(!value) return '成功';
		return value;
	}
    function OnSelectTab(sTitle) {
    	return;
        if ('销售记录' == sTitle) {
            $('#TableSale').datagrid({
                url: sys.context+'main/getSaleRecord',
                onLoadSuccess: function (oData) {
                    console.log('#TableSale onLoadSuccess()-->', oData);
                }
            });
            var pager =  $("#TableSale").datagrid('getPager');	// get the pager of datagrid
            pager.pagination({layout:['links']});
        } else if('进货记录' == sTitle){
            $('#TablePay').datagrid({
                url: sys.context+'main/getBuyRecord',
                onLoadSuccess: function (oData) {
                    console.log('#TablePay onLoadSuccess()-->', oData);
                },
                queryParams: {
                }
            });
            var pager =  $("#TablePay").datagrid('getPager');	// get the pager of datagrid
            pager.pagination({layout:['links']});
        }else {
            $("#TableDayLogs").datagrid({
                url:sys.context+'main/getDayReport',
                pageNumber:1,
                pageSize:10,
                queryParams: {
                    'page': sys.page||1,
                    'rows': sys.rows||10
                },	
                onLoadSuccess: function (oData) {
                    console.log('#TableDayLogs onLoadSuccess()-->', oData);		
                },columns: [
                    [{
                        field: 'time',
                        title: '日期',
                        width: 100,
                        align: 'center'
                    }, {
                        field: 'rounds',
                        title: '开局总数',
                        width: 100,
                        align: 'center'
                    }, {
                        field: 'consume',
                        title: '钻石消耗',
                        width: 100,
                        align: 'center'

                    },{
                        field: 'sale',
                        title: '出售钻石',
                        width: 100,
                        align: 'center'
                    },{
                        field: 'details',
                        title: '详情',
                        align: 'center',
                        formatter: function (value, row, index) {
                            var oBtn = $('<a>').text('详情').attr('href', 'javascript:void(0)').attr('onclick', 'OnClickDetails(' + index + ')').css('padding', '2px 0px');
                            oBtn.linkbutton({plain: false});
                            var oSpan = $('<span>');
                            oSpan.append(oBtn);
                            return oSpan.html();
                        }
                    }]
                ]
            });
            var pager =  $("#TableDayLogs").datagrid('getPager');	// get the pager of datagrid
            pager.pagination({layout:['links']});

        }
    }

    function OnClickDetails(index){
        var table = $("#TableDayLogs");
        table.datagrid('selectRow', index);
        var oRowData = table.datagrid('getSelected');
        var date = oRowData.log_date;
        window.location.href='#'+date;
    }


    function ParserDate(s) {
        if (!s) return new Date();
        var ss = (s.split('-'));
        var y = parseInt(ss[0], 10);
        var m = parseInt(ss[1], 10);
        var d = parseInt(ss[2], 10);
        if (!isNaN(y) && !isNaN(m) && !isNaN(d)) {
            return new Date(y, m - 1, d);
        } else {
            return new Date();
        }
    }

    function FormatterDate(date) {
        var y = date.getFullYear();
        var m = date.getMonth() + 1;
        var d = date.getDate();
        return y + '-' + (m < 10 ? ('0' + m) : m) + '-' + (d < 10 ? ('0' + d) : d);
    }

    function OnClickQuery(nType) {
        if (0 == nType) {
            var sDateFrom = $('#DateFromSale').datebox('getValue');
            var sDateTo = $('#DateToSale').datebox('getValue');
            $('#TableSale').datagrid({
                url: sys.context+'main/getSaleRecord',
                queryParams: {
                    'startDate': sDateFrom,
                    'endDate': sDateTo
                }
            });
        } else if (1 == nType) {
            var sDateFrom = $('#DateFromPay').datebox('getValue');
            var sDateTo = $('#DateToPay').datebox('getValue');
            $('#TablePay').datagrid({
                url: sys.context+'main/getBuyRecord',
                queryParams: {
                    'startDate': sDateFrom,
                    'endDate': sDateTo
                }
            });
        }
    }
    
    
</script>
</html>